<?php 
class HomePage extends Page {
    public static $db = array();
    
    public static $has_one = array(
		'AboutUs1' => 'SiteTree',
		'AboutUs2' => 'SiteTree'
	);
	
	function getCMSFields() {
		$fields = parent::getCMSFields();		
		
		$treedropdownfield = new TreeDropdownField("AboutUs1ID", "Choose a page to show about us on top:", "SiteTree");
//		$aboutUs = DataObject::get_one("AboutUs");
//		$treedropdownfield->setFilterFunction(create_function('$item', 'echo $item->Title . "  "; return $item->ParentID == 2;'));
		$fields->addFieldToTab("Root.Content.SubContents", $treedropdownfield);
		
		$treedropdownfield = new TreeDropdownField("AboutUs2ID", "Choose a page to show about us on right bottom:", "SiteTree");
		$fields->addFieldToTab("Root.Content.SubContents", $treedropdownfield);
		
		return $fields;
	}
	
	function AboutUs1Content($count = 90) {
		$aboutusId = $this->AboutUs1ID;
		if ($aboutusId == null) {
			return "";
		}
		$aboutus = DataObject::get_by_id('Page', $aboutusId);
		$content = DBField::create('Text', $aboutus->Content);
		return $content->LimitWordCount($count);
	}
	
	function AboutUs2Content($count = 90) {
		$aboutusId = $this->AboutUs2ID;
		if ($aboutusId == null) {
			return "";
		}
		$aboutus = DataObject::get_by_id('Page', $aboutusId);
		$content = DBField::create('Text', $aboutus->Content);
		return $content->LimitWordCount($count);
	}
}

class HomePage_Controller extends Page_Controller {
    
	public function ListContents() {
        $program = DataObject::get_one("Program");
        $children = ($program) ? DataObject::get("ProgramEntry", "ParentID = $program->ID") : false;
		return $children;
    }
	
	public function LatestNews($limit=2) {
		$news = $this->EntriesNews($limit);
		return $news;
	}
	
	public function EntriesNews($limit = '', $tag = '', $date = '') {
		$tagCheck = '';
		$dateCheck = '';
		
		if($tag) {
			$SQL_tag = Convert::raw2sql($tag);
			$tagCheck = "AND `BlogEntry`.Tags LIKE '%$SQL_tag%'";
		}
		
		if($date) {
			if(strpos($date, '-')) {
				$year = (int) substr($date, 0, strpos($date, '-'));
				$month = (int) substr($date, strpos($date, '-') + 1);
				
				if($year && $month) {
					$dateCheck = "AND MONTH(`BlogEntry`.Date) = $month AND YEAR(`BlogEntry`.Date) = $year";
				}
			} else {
				$year = (int) $date;
				if($year) {
					$dateCheck = "AND YEAR(`BlogEntry`.Date) = $year";
				}
			}
		}

		$news = DataObject::get_one("BlogHolder");		
		return DataObject::get("Page","`ParentID` = $news->ID $tagCheck $dateCheck","`BlogEntry`.Date DESC",'',"$limit");
	}
    
}
?>
